package com.sig.web.template;

import com.sig.common.util.SpringUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;

/**
 * 模板管理
 *
 * @author sig
 * @since 2019/2/22
 */
@Service
public class TemplateService {
    private StringTemplateLoader templateLoader = new StringTemplateLoader();
    private Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    public static TemplateService getInstance() {
        return SpringUtil.getBeanOfType(TemplateService.class);
    }

    @PostConstruct
    public void init() {
        configuration.setTemplateLoader(templateLoader);
        configuration.setDefaultEncoding("UTF-8");
        try {
            configuration.setSetting("template_update_delay", String.valueOf(0));
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    public <K, V> String parse(String key, String content, Map<K, V> params) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(content))
            return content;
        Template template = this.template(key);
        if (template == null) {
            templateLoader.putTemplate(key, content);
            template = this.template(key);
        }
        if (template == null)
            return content;
        try {
            FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return content;
    }

    private Template template(String key) {
        try {
            return configuration.getTemplate(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
